package com.xusheng.cli.controller.back;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.enums.PaySolution;
import com.xusheng.cli.common.validation.Save;
import com.xusheng.cli.common.validation.Update;
import com.xusheng.cli.entity.paymentChannelModule.PaymentChannel;
import com.xusheng.cli.req.PaymentChannelQueryReq;
import com.xusheng.cli.req.SetDefaultReq;
import com.xusheng.cli.service.PaymentChannelService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 支付通道相关接口
 *
 * @author lyh
 * @since 2023/4/24 0024 15:04
 */
@Validated
@RestController
@RequestMapping("/api/v1/paymentChannel")
public class PaymentChannelController {

    @Resource
    private PaymentChannelService channelService;

    /**
     * 按条件查询所有支付通道
     *
     * @param isGroup 是否按组查询
     * @param req     查询条件
     * @return 返回结果
     */
    @GetMapping("/all")
    public Result<List<PaymentChannel>> listAll(Boolean isGroup, PaymentChannelQueryReq req) {
        LambdaQueryWrapper<PaymentChannel> wrapper = Wrappers.<PaymentChannel>lambdaQuery()
                .orderByDesc(PaymentChannel::getCreateTime);
        if (req.getChannel() == null) {
            wrapper.eq(PaymentChannel::getChannel, 0)
                    .in(PaymentChannel::getType, PaySolution.WX_PAYMENT, PaySolution.ALIPAY_PAYMENT, PaySolution.UPAY_PAYMENT);
        } else {
            wrapper.eq(PaymentChannel::getChannel, req.getChannel());
        }
        if (isGroup != null && isGroup) {
            wrapper.groupBy(PaymentChannel::getMerchantNumber);
            wrapper.groupBy(PaymentChannel::getSecret);
        }
        return Result.success(channelService.list(wrapper));
    }

    /**
     * 按条件查询支付通道
     *
     * @param req 查询条件
     * @return 返回结果
     */
    @GetMapping("")
    public Result<MyPage<PaymentChannel>> list(PaymentChannelQueryReq req) {
        LambdaQueryWrapper<PaymentChannel> wrapper = Wrappers.<PaymentChannel>lambdaQuery()
                .eq(req.getMerchantId() != null, PaymentChannel::getMerchantNumber, req.getMerchantId())
                .gt(req.getStartTime() != null, PaymentChannel::getCreateTime, req.getStartTime())
                .lt(req.getEndTime() != null, PaymentChannel::getCreateTime, req.getEndTime())
                .orderByDesc(PaymentChannel::getCreateTime);
        return Result.success(channelService.page(req.getPage(), wrapper));
    }

    /**
     * 通过id获取支付通道
     *
     * @param id 编号
     * @return 返回结果
     */
    @GetMapping("/{id}")
    public Result<PaymentChannel> info(@PathVariable Serializable id) {
        return Result.success(channelService.getById(id));
    }

    /**
     * 保存支付通道
     *
     * @param channel 支付通道
     * @return 返回结果
     */
    @PostMapping("")
    public Result<Map<String, Object>> insert(@Validated(Save.class) @RequestBody PaymentChannel channel) {
        return Result.isSuccess(channelService.save(channel));
    }

    /**
     * 修改支付通道
     *
     * @param channel 支付通道
     * @return 返回结果
     */
    @PutMapping("")
    public Result<Map<String, Object>> update(@Validated(Update.class) @RequestBody PaymentChannel channel) {
        return Result.isSuccess(channelService.updateById(channel));
    }

    /**
     * 获取默认支付通道
     *
     * @return 返回结果
     */
    @GetMapping("/default")
    public Result<Dict> queryDefaultChannel(Integer channel) {
        Dict dict = Dict.create();
//		if (channel == null || channel == 0) {
        int num = 0;
        if (channel == null || channel == 0) {
            num = 0;
        } else {
            num = 1;
        }
        List<PaymentChannel> list = channelService.list(Wrappers.lambdaQuery(PaymentChannel.class)
                .in(PaymentChannel::getType, PaySolution.WX_PAYMENT, PaySolution.ALIPAY_PAYMENT, PaySolution.UPAY_PAYMENT)
                .eq(PaymentChannel::getChannel, num)
                .eq(PaymentChannel::getDefaultChannel, true));
        Map<PaySolution, PaymentChannel> map = list.stream().collect(Collectors.toMap(PaymentChannel::getType, p -> p));
        PaymentChannel wxpay = map.get(PaySolution.WX_PAYMENT);
        PaymentChannel alipay = map.get(PaySolution.ALIPAY_PAYMENT);
        PaymentChannel bankpay = map.get(PaySolution.UPAY_PAYMENT);
        dict.set("wxpay", wxpay != null ? wxpay.getId() : null);
        dict.set("alipay", alipay != null ? alipay.getId() : null);
        dict.set("bankpay", bankpay != null ? bankpay.getId() : null);
//		} else {
//			List<PaymentChannel> list = channelService.list(Wrappers.lambdaQuery(PaymentChannel.class)
//					.in(PaymentChannel::getType, PaySolution.H5_WX, PaySolution.H5_ALI, PaySolution.H5_UPAY)
//					.eq(PaymentChannel::getChannel, 1)
//					.eq(PaymentChannel::getDefaultChannel, true));
//			Map<PaySolution, PaymentChannel> map = list.stream().collect(Collectors.toMap(PaymentChannel::getType, p->p));
//			PaymentChannel wxpay = map.get(PaySolution.H5_WX);
//			PaymentChannel alipay = map.get(PaySolution.H5_ALI);
//			PaymentChannel bankpay = map.get(PaySolution.H5_UPAY);
//			dict.set("wxpay", wxpay != null ? wxpay.getId() : null);
//			dict.set("alipay", alipay != null ? alipay.getId() : null);
//			dict.set("bankpay", bankpay != null ? bankpay.getId() : null);
//		}
        return Result.success(dict);
    }

    /**
     * 设置默认支付通道
     *
     * @return 返回结果
     */
    @PutMapping("/default")
    public Result<Dict> setDefault(@Validated(Update.class) @RequestBody SetDefaultReq setDefaultReq) {
        if (setDefaultReq.getChannel() == null) {
            setDefaultReq.setChannel(0);
        }
        channelService.lambdaUpdate().set(PaymentChannel::getDefaultChannel, false)
                .eq(PaymentChannel::getChannel, setDefaultReq.getChannel())
                .update();
        channelService.lambdaUpdate().set(PaymentChannel::getDefaultChannel, true)
                .eq(PaymentChannel::getChannel, setDefaultReq.getChannel())
                .in(PaymentChannel::getId, setDefaultReq.getAlipay(), setDefaultReq.getBankpay(), setDefaultReq.getWxpay())
                .update();
        return Result.success();

    }

    /**
     * 根据id删除支付通道
     *
     * @param id 编号
     * @return 返回结果
     */
    @DeleteMapping("/{id}")
    public Result<Map<String, Object>> delete(@PathVariable Long id) {
        PaymentChannel channel = new PaymentChannel();
        channel.setId(id);
        return Result.isSuccess(channelService.removeById(channel));
    }

}

